package com.rc.saas.tenant.controller.tenant;

import com.google.code.kaptcha.Constants;
import com.google.code.kaptcha.Producer;
import com.rc.saas.tenant.base.TenantBaseController;
import com.rc.saas.tenant.common.base.HttpConstant;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;

/**
 * 验证码
 */
@Controller
@RequestMapping(value = "/captcha")
public class CaptchaController extends TenantBaseController {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private Producer captchaProducer;

    /**
     * 生成验证码
     *
     * @param request
     * @param response
     * @param model
     * @return
     * @throws IOException
     */
    @RequestMapping(value = "/genCaptcha")
    public ModelAndView getCaptcha(HttpServletRequest request, HttpServletResponse response, Model model)
            throws IOException {

        //http://blog.sina.com.cn/s/blog_b3bf01600102z3cj.html
        //Java8中的一个潜在的Bug，具体原因是Java8中生成图形验证码时会在当前的操作系统中寻找验证码所需要的字体，如果没有找到，则会抛出上面的空指针异常。
        //解决方案：只需在当前操作系统中安装相应的字体即可解决该问题。
        //（1）Red Hat系统：yum install fontconfig 执行该命令安装字体即可
        //（2）Ubuntu系统： apt-get install -y libfontconfig 执行该命令安装字体即可
        //（3）Centos系统：yum install fontconfig 执行该命令安装字体即可

        response.setDateHeader("Expires", 0);

        // Set standard HTTP/1.1 no-cache headers.

        response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
        // Set IE extended HTTP/1.1 no-cache headers (use addHeader).

        response.addHeader("Cache-Control", "post-check=0, pre-check=0");
        // Set standard HTTP/1.0 no-cache header.

        response.setHeader("Pragma", "no-cache");
        // return a jpeg

        response.setContentType("image/jpeg");
        // create the text for the image

        String capText = captchaProducer.createText();
        // store the text in the session

        request.getSession().setAttribute(HttpConstant.KAPTCHA_SESSION_KEY, capText);
        // create the image with the text

        BufferedImage bi = captchaProducer.createImage(capText);
        ServletOutputStream out = response.getOutputStream();
        // write the data out

        ImageIO.write(bi, "jpg", out);
        try {
            out.flush();
        } finally {
            out.close();
        }
        return null;
    }
}